package cn.bdqn.demo.seckill;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class StockCacheService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    public StockCacheService(StringRedisTemplate stringRedisTemplate,StockBean stockBean) {
        this.stringRedisTemplate = stringRedisTemplate;
        set(stockBean.getProductId(),stockBean.getInitStock());
    }

    /**
     * 从redis中获取缓存的库存数量
     * @param productId
     * @return 库存数量
     */
    public int get(String productId) {
        return Integer.parseInt(stringRedisTemplate.opsForValue().get(productId));
    }

    /**
     * 更新缓存中的库存数量
     * @param productId
     * @param stock
     */
    public void set(String productId, int stock) {
        stringRedisTemplate.opsForValue().set(productId,""+stock);
    }
}
